package com.u.social.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.u.social.article.service.IArticleStatsService;
import com.u.social.article.entity.ArticleLikes;
import com.u.social.article.entity.ArticleStats;
import com.u.social.article.mapper.ArticleLikesMapper;
import com.u.social.article.service.IArticleLikesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.u.social.article.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-02-25
 */
@Slf4j
@Service
public class ArticleLikesServiceImpl extends ServiceImpl<ArticleLikesMapper, ArticleLikes> implements IArticleLikesService {

    @Autowired
    private IRedisService redisService;

    @Autowired
    private IArticleStatsService articleStatsService;
    @Override
    public Boolean saveLikeStatus(Long userId, Long likeUserId, Long articleId, Integer status) {
        boolean isLike = Objects.equals(status, 1);

        if(isLike){
            redisService.incrementHash("article_like_count", articleId.toString(), 1);
        }else {
            Object articleLikeCount = redisService.getHash("article_like_count", articleId.toString());
            if(articleLikeCount != null && Integer.parseInt(articleLikeCount.toString()) > 0) {
                redisService.incrementHash("article_like_count", articleId.toString(), -1);
            }
        }
        String hashKey = userId.toString() + ":" + likeUserId.toString() + ":" + articleId.toString();
        redisService.putHash("article_like_status", hashKey, status);
        return true;
    }

    /**
     * 定时任务，每隔1分钟执行一次，同步点赞状态到数据库
     */
    @Scheduled(fixedRate = 1000 * 60) // 每隔1分钟执行一次
    public void syncLikeStatus() {
        // 1. 批量同步点赞状态到数据库
        List<ArticleLikes> articleLikesList = new ArrayList<>();

        redisService.getAllHash("article_like_status").forEach((k, v) -> {
            String[] keys = k.toString().split(":");
            Long userId = Long.parseLong(keys[0]);
            Long likeUserId = Long.parseLong(keys[1]);
            Long articleId = Long.parseLong(keys[2]);
            Integer status = Integer.parseInt(v.toString());

            ArticleLikes articleLikes = this.getOne(new QueryWrapper<ArticleLikes>().eq("user_id", userId)
                    .eq("like_user_id", likeUserId));


            if(articleLikes == null) {
                articleLikes = new ArticleLikes();
            }
            articleLikes.setLikeUserId(likeUserId);
            articleLikes.setArticleId(articleId);
            articleLikes.setStatus(status);

            articleLikesList.add(articleLikes);
        });

        if(!articleLikesList.isEmpty()){
            this.saveOrUpdateBatch(articleLikesList);
        }
        log.info("syncLikeStatus success: {}", articleLikesList);

        // 2. 批量同步点赞数量到数据库
        List<ArticleStats> articleStatsList = new ArrayList<>();
        redisService.getAllHash("article_like_count").forEach((k, v) -> {
            Long articleId = Long.parseLong(k.toString());
            Integer likeCount = Integer.parseInt(v.toString());

            ArticleStats articleStats  = articleStatsService.getOne(new QueryWrapper<ArticleStats>().eq("article_id", articleId));
            if(articleStats == null) {
                articleStats = new ArticleStats();
            }

            articleStats.setLikeCount(likeCount);
            articleStatsList.add(articleStats);
        });

        if(!articleStatsList.isEmpty()){
            articleStatsService.saveOrUpdateBatch(articleStatsList);
        }

    }
}
